package com.yami.shop.mystery.platform.task;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.xxl.job.core.handler.annotation.XxlJob;
import com.yami.shop.common.util.PageParam;
import com.yami.shop.mystery.common.model.MysteryBoxOrder;
import com.yami.shop.mystery.common.model.MysteryBoxUserArk;
import com.yami.shop.mystery.common.service.MysteryBoxOpenRecordService;
import com.yami.shop.mystery.common.service.MysteryBoxUserArkService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * 盲盒定时任务
 * @author wxf
 * @date 2023/4/13 16:36
 */
@Slf4j
@Component
@AllArgsConstructor
public class MysteryBoxTask {

    private final MysteryBoxUserArkService mysteryBoxUserArkService;

    private final MysteryBoxOpenRecordService recordService;

    /**
     * 开盲盒
     */
    @XxlJob("openBoxTask")
    public void openBoxTask() {

        log.info("开盲盒定时任务开始");
        while (true) {
            PageParam<MysteryBoxUserArk> page = new PageParam<>();
            page.setSize(30);
            page.setCurrent(1);
            IPage<MysteryBoxUserArk> userArkIPage = mysteryBoxUserArkService.selectNeedInitializePage(page, new MysteryBoxUserArk());
            if (userArkIPage == null || userArkIPage.getRecords().isEmpty()) {
                log.info("无待处理盲盒");
                break;
            }
            List<MysteryBoxOrder> list = new ArrayList<>();
            for (MysteryBoxUserArk userArk : userArkIPage.getRecords()) {
                MysteryBoxOrder mysteryBoxOrder = new MysteryBoxOrder();
                mysteryBoxOrder.setMysteryBoxId(userArk.getBid());
                mysteryBoxOrder.setUserId(userArk.getUid());
                mysteryBoxOrder.setProdCount(userArk.getCount() - userArk.getOpenCount());
                if (mysteryBoxOrder.getProdCount() > 0) {
                    list.add(mysteryBoxOrder);
                }
            }
            recordService.initMysteryBoxOpenRecord(list);
            try {
                Thread.sleep(10000);
            } catch (InterruptedException e) {
            }
        }
        log.info("开盲盒定时任务结束");
    }
}
